package com.changgou.system.filter;

import com.changgou.system.util.JwtUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

//自定义过滤器
@Component
public class CustomFilter implements GlobalFilter,Ordered{

    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取请求对象
        ServerHttpRequest request = exchange.getRequest();
        //获取响应对象
        ServerHttpResponse response = exchange.getResponse();
        //判断当前请求是否是登录请求,是则放行
        if(request.getURI().getPath().contains("/admin/login")){
            //放行
            chain.filter(exchange);
        }
        //获取当前的所有请求头信息
        HttpHeaders headers = request.getHeaders();
        //获取jwt令牌信息
        String JwtToken = headers.getFirst("token");

        if(StringUtils.isEmpty(JwtToken)){
           //判断jwt令牌是否存在,不存在则提示错误信息 UNAUTHORIZED:当前用户登录失败
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
       }
        //存在则解析jwt令牌,判断jwt令牌是否合法,不合法则返回错误信息
        //解析令牌
        try {
            JwtUtil.parseJWT(JwtToken);
        } catch (Exception e) {
            e.printStackTrace();
            //解析失败
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        //合法则放行
        return chain.filter(exchange);
    }

    //getOrder 这个方法是设置过滤器的执行优先级,值越小,优先级越高
    public int getOrder() {
        return 1;
    }
}
